package sdk

import (
	"bytes"
	"encoding/json"
	"errors"

	"gitee.com/wz-open-platform/wzopen-sdk-go/constants"
	"gitee.com/wz-open-platform/wzopen-sdk-go/model"
	"gitee.com/wz-open-platform/wzopen-sdk-go/tools"
	"github.com/tidwall/gjson"
)

// 开始充电
func (c *client) ChargeStart(req *model.ChargeStart) (resp *model.Response, err error) {
	method := "POST"
	postparams := tools.StructToMap(req)
	postparams = c.buildPostParam(postparams)
	postparamBytes, err := json.Marshal(postparams)
	if err != nil {
		return
	}
	bytes, err := tools.DoHttp(c.baseURL+"/open/charge/start", method, map[string]string{}, bytes.NewBuffer([]byte(postparamBytes)), nil)
	if err != nil {
		return
	}
	if gjson.GetBytes(bytes, "code").Int() != constants.SucceedCode {
		err = errors.New(gjson.GetBytes(bytes, "message").String())
		return
	}
	err = json.Unmarshal(bytes, &resp)
	return
}

// 结束充电
func (c *client) ChargeStop(req *model.ChargeStop) (resp *model.Response, err error) {
	method := "POST"
	postparams := tools.StructToMap(req)
	postparams = c.buildPostParam(postparams)
	postparamBytes, err := json.Marshal(postparams)
	if err != nil {
		return
	}
	bytes, err := tools.DoHttp(c.baseURL+"/open/charge/stop", method, map[string]string{}, bytes.NewBuffer([]byte(postparamBytes)), nil)
	if err != nil {
		return
	}
	if gjson.GetBytes(bytes, "code").Int() != constants.SucceedCode {
		err = errors.New(gjson.GetBytes(bytes, "message").String())
		return
	}
	err = json.Unmarshal(bytes, &resp)
	return
}
